﻿using System;
using System.Drawing;
using System.Windows.Forms;
using SnapDesktop.ImgurApi;

namespace SnapDesktop
{
    internal class SnapApplication : Form
    {
        private readonly KeyboardHook _hook = new KeyboardHook();
        private readonly NotifyIcon _trayIcon = new NotifyIcon();
        private readonly Uploader _uploader = new Uploader("b82dca2775438b7");

        public SnapApplication()
        {
            TopMost = true;
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
            ShowInTaskbar = false;
            FormBorderStyle = FormBorderStyle.None;
            Opacity = 0;

            _trayIcon.Icon = new Icon("Resources/Icon.ico");
            _trayIcon.Text = "Snap Desktop";
            _trayIcon.Visible = true;


            var trayMenu = new ContextMenu();
            _trayIcon.ContextMenu = trayMenu;
            trayMenu.MenuItems.Add("Exit", OnExit);

            _hook.KeyPressed += hook_KeyPressed;
            _hook.RegisterHotKey(ModKeys.Control | ModKeys.Shift, Keys.D4);
        }

        public Image SnappedImage { get; set; }
        public Rectangle SnapArea { get; set; }
        public bool Canceled { get; set; }
        public string Link { get; set; }

        private void OnExit(object sender, EventArgs e)
        {
            _trayIcon.Visible = false;
            Application.Exit();
        }

        public void hook_KeyPressed(object sender, KeyPressedEventArgs e)
        {
            StartSnap();
        }

        private void StartSnap()
        {
            new SnapSelector(this).ShowDialog();
            if (Canceled)
            {
                Reset();
                return;
            }
            SnappedImage = new ImageSnapper().Snap(SnapArea);
            try
            {
                Link = _uploader.Upload(SnappedImage).Data.Link;
                Balloon(Link);
                Clipboard.SetText(Link);
            }
            catch
            {
                //TODO: Balloon noting error
            }
            finally
            {
                Reset();
            }
        }

        private void Reset()
        {
            Canceled = false;
            SnappedImage = null;
            SnapArea = new Rectangle();
        }

        private void Balloon(string message)
        {
            _trayIcon.ShowBalloonTip(6000, "Upload Complete", message, ToolTipIcon.Info);
        }
    }
}